package com.dhz.common.dao.mybatis.handler;

import com.dhz.common.model.DbEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class EnumsTypeHandler<E extends Enum<E> & DbEnum<E>> extends BaseTypeHandler<E> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        rs.getInt(columnName);

        return getNullableResult(rs.getInt(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getNullableResult(rs.getInt(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getNullableResult(cs.getInt(columnIndex));
    }

    /**
     * 子类必须实现的功能，根据value获取枚举值
     * @param value int value
     * @return E
     */
    public abstract E getNullableResult(int value);

}
